package com.ww.springboot.rabbitmq.config;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MQ 配置类
 * date:
 * version: 1.0.0
 * description: RabbitMQ配置类
 * @author ZH500
 */
@Configuration
public class RabbitMqConfig2 {

    @Bean(name = "pddRabbitAdmin")
    public RabbitAdmin rabbitAdmin(@Qualifier("pddConnectionFactory") ConnectionFactory connectionFactory){
        return new RabbitAdmin(connectionFactory);
    }

    /**
     * pdd_test 连接工厂
     */
    @Bean(name = "pddConnectionFactory")
    public ConnectionFactory pddConnectionFactory(@Value("${pdd.rabbitmq.host}") String host,
                                                  @Value("${pdd.rabbitmq.port}") int port,
                                                  @Value("${pdd.rabbitmq.username}") String username,
                                                  @Value("${pdd.rabbitmq.password}") String password,
                                                  @Value("${pdd.rabbitmq.virtual-host}") String vHost) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(vHost);
        connectionFactory.setPublisherReturns(true);
        return connectionFactory;
    }


    /**
     *    pdd_test生产者
     */
    @Bean(name = "pddRabbitTemplate")
    public RabbitTemplate pddRabbitTemplate(@Qualifier("pddConnectionFactory") ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }

    /**
     * pdd_test 消费者
     */
    @Bean(name = "pddListenerFactory")
    public SimpleRabbitListenerContainerFactory pddListenerFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            @Qualifier("pddConnectionFactory") ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory listenerContainerFactory = new SimpleRabbitListenerContainerFactory();
        //设置手动ack
        listenerContainerFactory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        configurer.configure(listenerContainerFactory, connectionFactory);
        return listenerContainerFactory;
    }

}
